import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {HttpClient} from '@angular/common/http';
import {ActivatedRoute, Router} from '@angular/router';
import {Location} from '@angular/common';

@Component({
  selector: 'app-add',
  templateUrl: './add.component.html',
  styleUrls: ['./add.component.scss']
})
export class AddComponent implements OnInit {
  validateForm: FormGroup;
  passwordVisible = false;
  id: any;

  constructor(
    private fb: FormBuilder,
    private http: HttpClient,
    private router: Router,
    private location: Location,
    private route: ActivatedRoute,
  ) {
    this.validateForm = this.fb.group({
      id: [],
      createAt: [],
      url: ['jdbc:mysql://localhost:3306/testa', [Validators.required]],
      driver: ['com.mysql.cj.jdbc.Driver', [Validators.required]],
      username: ['root', [Validators.required]],
      password: ['root', [Validators.required]],
      description: ['描述', [Validators.required]],
    });
  }

  ngOnInit() {
    this.route.paramMap.subscribe(res => {
      this.id = res.get('id');
      if (this.id) {
        this.loadData();
      }
    });
  }

  submitForm(value: any): void {
    for (const key in this.validateForm.controls) {
      if (key) {
        this.validateForm.controls[key].markAsDirty();
        this.validateForm.controls[key].updateValueAndValidity();
      }
    }
    this.http.post('/api/database/save', value).subscribe(() => {
      this.router.navigate(['/database']);
    });
  }

  resetForm(e: MouseEvent): void {
    e.preventDefault();
    this.validateForm.reset();
    for (const key in this.validateForm.controls) {
      if (key) {
        this.validateForm.controls[key].markAsPristine();
        this.validateForm.controls[key].updateValueAndValidity();
      }
    }
  }

  backward() {
    this.location.back();
  }

  loadData() {
    this.http.get('/api/database/' + this.id).subscribe(res => {
      this.validateForm.patchValue(res);
    });
  }
}
